<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="任务编号" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入任务编号" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入任务名称" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="任务类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择任务类型" clearable class="!w-240px">
          <el-option v-for="dict in getDictOptions(DICT_TYPE.BPM_TASK_TYPE)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable class="!w-240px">
          <el-option v-for="dict in getDictOptions(DICT_TYPE.BPM_TASK_STATUS)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="负责人" prop="adminId">
        <el-tree-select :props="defaultProps" v-model="queryParams.adminId" :data="userList"
          :render-after-expand="false" placeholder="请选择负责人" class="!w-240px" />
      </el-form-item>
      <el-form-item label="确认人" prop="confirmId">
        <el-tree-select :props="defaultProps" v-model="queryParams.confirmId" :data="userList"
          :render-after-expand="false" placeholder="请选择确认人" class="!w-240px" />
      </el-form-item>
      <el-form-item label="关注人" prop="attentionId">
        <el-tree-select :props="defaultProps" v-model="queryParams.attentionId" :data="userList"
          :render-after-expand="false" placeholder="请选择关注人" class="!w-240px" />
      </el-form-item> -->
      <!-- <el-form-item label="标签" prop="tagId">
        <el-tree-select v-model="queryParams.tagId" placeholder="请输入标签" :data="options" :render-after-expand="false"
          class="!w-240px" />
      </el-form-item> -->
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker v-model="queryParams.startTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker v-model="queryParams.endTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime"
          class="!w-240px" />
      </el-form-item>

      <!-- <el-form-item label="项目名称" prop="processInstanceId">
        <el-input v-model="queryParams.processInstanceId" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item> -->

      <el-form-item label="项目名称" prop="projectId">
        <el-select v-model="queryParams.projectId" placeholder="请选择项目名称" class="!w-240px" clearable>
          <el-option v-for="dict in projectOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery" v-hasPermi="['bpm:task-info:query']">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['bpm:task-info:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['bpm:task-info:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <!-- <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="任务编号" align="center" prop="code" />
      <el-table-column label="任务名称" align="center" prop="name" />
      <el-table-column label="任务类型" align="center" prop="type" />
      <el-table-column label="表单类型" align="center" prop="formType" />
      <el-table-column label="负责人" align="center" prop="adminId" />
      <el-table-column label="确认人" align="center" prop="confirmId" />
      <el-table-column label="关注人" align="center" prop="attentionId" />
      <el-table-column label="任务状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BPM_TASK_STATUS" :value="scope.row.status" />
        </template>
</el-table-column>
<el-table-column label="开始时间" align="center" prop="startTime" :formatter="dateFormatter" width="180px" />
<el-table-column label="结束时间" align="center" prop="endTime" :formatter="dateFormatter" width="180px" />
<el-table-column label="任务标签" align="center" prop="tagId" />
<el-table-column label="流程实例" align="center" prop="processInstanceId" />
<el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
<el-table-column label="任务描述" align="center" prop="description" />
<el-table-column label="操作" align="center">
  <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row.id)"
            v-hasPermi="['bpm:task-info:update']">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['bpm:task-info:delete']">
            删除
          </el-button>
        </template>
</el-table-column>
</el-table>
</ContentWrap> -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column label="项目名称" align="center" prop="projectName" min-width="180px" fixed="left" />
      <el-table-column label="任务编号" align="center" prop="code" min-width="200px" />
      <el-table-column label="任务名称" align="center" prop="name" min-width="180px" />
      <!-- <el-table-column
        label="流程分类"
        align="center"
        prop="categoryName"
        min-width="100"
        fixed="left"
      /> -->
      <el-table-column label="流程名称" align="center" prop="categoryName" min-width="160px" />
      <el-table-column label="流程状态" prop="status" width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="发起时间" align="center" prop="startTime" width="180" :formatter="dateFormatter" />
      <el-table-column label="结束时间" align="center" prop="endTime" width="180" :formatter="dateFormatter" />
      <el-table-column align="center" label="耗时" prop="durationInMillis" width="160">
        <template #default="scope">
          {{ scope.row.durationInMillis > 0 ? formatPast2(scope.row.durationInMillis) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="当前审批任务" align="center" prop="tasks" min-width="120px">
        <template #default="scope">
          <el-button type="primary" v-for="task in scope.row.tasks" :key="task.id" link>
            <span>{{ task.name }}</span>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="流程编号" align="center" prop="id" min-width="100px" />
      <el-table-column label="操作" align="center" fixed="right" width="180">
        <template #default="scope">
          <el-button link type="primary" v-hasPermi="['bpm:process-instance:cancel']" @click="handleDetail(scope.row)">
            详情
          </el-button>
          <el-button link type="primary" v-if="scope.row.status === 1" v-hasPermi="['bpm:process-instance:query']"
            @click="handleCancel(scope.row)">
            取消
          </el-button>
          <el-button link type="primary" v-else @click="handleCreate(scope.row.processInstanceId)">
            重新发起
          </el-button>
          <el-button link type="primary"
            :disabled="isButtonDisabled(scope.row.processInstanceId) || scope.row.status === 2 || scope.row.status === 9"
            @click="handleReminders(scope.row.processInstanceId)">
            催办
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <TaskInfoForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { ElMessageBox } from 'element-plus'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'

import { dateFormatter, formatPast2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { TaskInfoApi, TaskInfoVO } from '@/api/bpm/taskinfo'
import TaskInfoForm from './TaskInfoForm.vue'
import { DICT_TYPE, getDictOptions } from '@/utils/dict'
import * as UserApi from '@/api/system/user'
import { TagGroupInfoApi, TagGroupInfoVO } from '@/api/bpm/taggroupinfo'
import { ProjectInfoApi } from '@/api/bpm/projectinfo'
import { useRoute } from 'vue-router';

/** 流程任务信息 列表 */
defineOptions({ name: 'BpmTaskInfo' })

const router = useRouter() // 路由

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<TaskInfoVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  name: undefined,
  type: undefined,
  adminId: undefined,
  confirmId: undefined,
  attentionId: undefined,
  status: undefined,
  startTime: [],
  endTime: [],
  tagId: undefined,
  processInstanceId: undefined,
  description: undefined,
  projectId: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

//负责人下拉选
const userList = ref<any>([]) // 用户列表
const defaultProps = ref({
  children: 'childrenDepts',
  label: 'deptName',
  value: 'id'
})

const getUserList = async () => {
  const response = await UserApi.getSimpleUserListCopy()
  userList.value = response.map((item) => {
    item.childrenDepts = item.childrenDepts.concat(fmtUserName(item.childrenUsers) || [])
    return {
      ...item,
      childrenDepts:
        item.childrenDepts && item.childrenDepts.length
          ? item.childrenDepts.map((it) => {
            return getEndDepartments(it)
          })
          : fmtUserName(item.childrenUsers) || []
    }
  })
}

const getEndDepartments = (obj: any) => {
  if (!obj.childrenDepts || obj.childrenDepts.length == 0) {
    obj.childrenDepts = fmtUserName(obj.childrenUsers)
  } else {
    obj.childrenDepts = obj.childrenDepts
      .concat(fmtUserName(obj.childrenUsers) || [])
      .map((item) => {
        return getEndDepartments(item)
      })
  }
  return obj
}

const fmtUserName = (childrenUsers) => {
  if (!childrenUsers || !childrenUsers.length) return []
  return childrenUsers.map((item) => {
    return {
      ...item,
      deptName: item.nickname || ''
    }
  })
}

const projectOptions = ref([
  {
    value: undefined,
    label: undefined
  }
]) // 项目列表

const getProjectInfo = async () => {
  let params = {
    pageNo: 1,
    pageSize: 100
  }
  let response = await ProjectInfoApi.getProjectInfoPage(params)
  projectOptions.value = response.list.map((item) => ({
    value: item.id,
    label: item.name
  }))
}

//标签组下拉选
const cascaderValue = ref([])
const options = ref([])

const getAllTagInfo = async () => {
  let response = await TagGroupInfoApi.getAllTagGroupInfo()
  options.value = response.map((tagGroup) => ({
    value: tagGroup.id,
    label: tagGroup.name,
    children: tagGroup.children.map((tag) => ({
      value: tag.tagId,
      label: tag.tagName
    }))
  }))
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TaskInfoApi.getTaskInfoPage(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('Failed to fetch task info:', error)
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await TaskInfoApi.deleteTaskInfo(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await TaskInfoApi.exportTaskInfo(queryParams)
    download.excel(data, '流程任务信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const route = useRoute() // 路由

/** 初始化 **/
onMounted(() => {
  getUserList()
  getAllTagInfo()
  getProjectInfo()
  if (route.query.id) {
    queryParams.status = route.query.id
    getList()
  } else {
    getList()
  }
})

/** 查看详情 */
const handleDetail = (row) => {
  router.push({
    name: 'BpmProcessInstanceDetail',
    query: {
      id: row.processInstanceId
    }
  })
}

/** 取消按钮操作 */
const handleCancel = async (row) => {
  // 二次确认
  const { value } = await ElMessageBox.prompt('请输入取消原因', '取消流程', {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    inputPattern: /^[\s\S]*.*\S[\s\S]*$/, // 判断非空，且非空格
    inputErrorMessage: '取消原因不能为空'
  })
  // 发起取消
  await ProcessInstanceApi.cancelProcessInstanceByStartUser(row.processInstanceId, value)
  message.success('取消成功')
  // 刷新列表
  await getList()
}

/** 重新发起操作 */
const handleCreate = (id) => {
  router.push({
    name: 'BpmProcessInstanceCreate',
    query: { processInstanceId: id }
  })
}

/** 催办 */
const buttonDisabledMap = ref({}) // 保存每个按钮的禁用状态

const isButtonDisabled = (id) => {
  return buttonDisabledMap.value[id] || false
}

const handleReminders = async (id) => {
  if (isButtonDisabled(id)) return
  buttonDisabledMap.value[id] = true

  try {
    await TaskInfoApi.goReminder({ procInsId: id })
    message.success('催办成功')
  } catch (error) {
    message.error('催办失败')
  }
  setTimeout(() => {
    buttonDisabledMap.value[id] = false
  }, 86400000)
}

</script>
